package com.cmcc.passenger.ui.tripoption.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.cmcc.passenger.data.entity.Item
import com.cmcc.passenger.databinding.ListItemTripOptionButtonBinding
import com.cmcc.shared.SdkManager
import com.cmcc.shared.utils.clickWithTrigger

class RemarkItemAdapter<T : Item> :
    ListAdapter<T, RemarkItemAdapter<T>.ViewHolder>(RemarkItemDiffCallback()) {
    var checkedPosition = -1

    private var listener: OnRemarkItemCheckedListener<T>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ListItemTripOptionButtonBinding.inflate(
                LayoutInflater.from(
                    parent.context
                ), parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val model = getItem(position)
        val language = SdkManager.getLanguage()
        when (language) {
            SdkManager.LANGUAGE_ENG ->
                holder.binding.carAny.text = model?.contentEnUs
            SdkManager.LANGUAGE_ZH_CN ->
                holder.binding.carAny.text = model?.contentZhCn
            SdkManager.LANGUAGE_ZH_TW ->
                holder.binding.carAny.text = model?.contentZhHk
        }

        holder.bind(model)
        if (checkedPosition == -1) {
            holder.itemView.isSelected = false
        } else {
            holder.itemView.isSelected = checkedPosition == position
        }
        holder.itemView.clickWithTrigger {
            if (checkedPosition != position) {
                holder.itemView.isSelected = true
                checkedPosition = position
                listener?.onItemChecked(model, position)
                notifyDataSetChanged()
            }
        }
    }

    fun addOnOptionItemCheckedListener(listener: OnRemarkItemCheckedListener<T>) {
        this.listener = listener
    }

    inner class ViewHolder(val binding: ListItemTripOptionButtonBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(model: T) {
        }
    }

}

interface OnRemarkItemCheckedListener<T> {
    fun onItemChecked(model: T, position: Int)
}


class RemarkItemDiffCallback<T : Item> : DiffUtil.ItemCallback<T>() {
    override fun areItemsTheSame(oldItem: T, newItem: T): Boolean {
        return true
    }

    override fun areContentsTheSame(oldItem: T, newItem: T): Boolean {
        return true
    }

}